package com.xtxbyj;

import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.ExifDirectoryBase;
import com.drew.metadata.exif.ExifSubIFDDirectory;
import com.drew.metadata.file.FileSystemDirectory;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;

public class ImageTool {
    private static SimpleDateFormat dtf1 = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
    private static SimpleDateFormat dtf2= new SimpleDateFormat("yyyy-MM");

    public static String getDate(File image){

        Metadata metadata = null;
        try {
            metadata = ImageMetadataReader.readMetadata(image);
        } catch (ImageProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (metadata==null){
            return null;
        }

        // 如果能够获取exfi的日期数据，以该日期为准
        ExifDirectoryBase exifDir = metadata.getFirstDirectoryOfType(ExifSubIFDDirectory.class);
        if (exifDir!=null) {
            String date = exifDir.getString(ExifDirectoryBase.TAG_DATETIME_ORIGINAL);
            if (date != null) {
                try {
                    return dtf2.format(dtf1.parse(date));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }

        FileSystemDirectory fileDir = metadata.getFirstDirectoryOfType(FileSystemDirectory.class);
        if (fileDir!=null) {
            Object date = fileDir.getObject(FileSystemDirectory.TAG_FILE_MODIFIED_DATE);
            if (date != null) {
                try {
                    return dtf2.format(date);
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }
}
